#include "serverthread.h".h"
#include <QDebug>

ServerThread::ServerThread(QTcpSocket *socket, QObject *parent)
    : QThread(parent), clientSocket(socket)
{
    connect(clientSocket, &QTcpSocket::readyRead, this, &ServerThread::onReadyRead);
    connect(clientSocket, &QTcpSocket::disconnected, this, &ServerThread::onDisconnected);
}

ServerThread::~ServerThread()
{
    clientSocket->deleteLater();
}

void ServerThread::run()
{
    exec();  // 启动线程事件循环
}

void ServerThread::onReadyRead()
{
    QTcpSocket *clientSocket = qobject_cast<QTcpSocket*>(sender());
    if (clientSocket) {
        QByteArray data = clientSocket->readAll();
        qDebug() << "Received data from" << clientSocket->peerAddress().toString() << ":" << data;

        QDataStream in(data);
        Header header;
        in >> header;

        switch (header) {
        case USER_ID_FOR_CHAT_HISTORY:

            {
                qDebug() << "get Header : Processing USER_ID_FOR_CHAT_HISTORY from " << clientSocket->peerAddress().toString();
                int userOneId,UserTwoId;
                in >> userOneId >> UserTwoId;
                handleChatHistory(clientSocket,userOneId,UserTwoId);
                // 处理聊天记录请求
                break;
            }


        case USER_ID_FOR_INFORMATION:

            {
                qDebug() << "get Header : Processing USER_ID_FOR_INFORMATION from" << clientSocket->peerAddress().toString();
                // 处理用户信息请求
                int userId;
                in >> userId;
                handleInformation(clientSocket,userId);
                break;
            }

            // 处理其他命令类型
        case USER_ID_FOR_FRIEND_LIST:

            {
                qDebug() << "get Header : USER_ID_FOR_FRIEND_LIST" << clientSocket->peerAddress().toString();
                int UserId;
                in >> UserId;
                handleFriendList(clientSocket,UserId);
                break;
            }


        case INSERT_CHAT_HISTORY:

            {
                qDebug() << "get Header : INSERT_CHAT_HISTORY" << clientSocket->peerAddress().toString();
                int UserId1,UserId2;
                in >> UserId1 >> UserId2;
                ChatHistory chatHistoryData;
                in >> chatHistoryData;
                handleInsertChatHistory(clientSocket,UserId1,UserId2,chatHistoryData);
                break;
            }

        case UPDATE_USER_INFORMATION_WITH_ID:

            {
                qDebug() << "get Header : UPDATE_USER_INFORMATION_WITH_ID" << clientSocket->peerAddress().toString();
                int UserId4;
                in >> UserId4;
                User u;
                in >> u;
                handleUpdateUserInformation(clientSocket,u);
                break;
            }

        case INSERT_USER_INFORMATION:
        {
            qDebug() << "get header : INSERT_USER_INFORMATION" << clientSocket->peerAddress().toString();
            User u;
            in >> u;
            handleInsertUserInformation(clientSocket, u);
            break;
        }

        case INSERT_FRIEND_RELATION:
        {
            qDebug() << "get header : INSERT_FRIEND_RELATION" << clientSocket->peerAddress().toString();
            int user_one_id,user_two_id;
            in >> user_one_id >> user_two_id;
            handleInsertFriendRelation(clientSocket,user_one_id,user_two_id);
            break;
        }

        case DELETE_FRIEND_RELATION:
        {
            qDebug() << "get header : DELETE_FRIEND_RELATION" << clientSocket->peerAddress().toString();
            int user_one_id,user_two_id;
            in >> user_one_id >> user_two_id;
            handleDeleteFriendRelation(clientSocket,user_one_id,user_two_id);
            break;
        }

        default:

            {
                qDebug() << "get Header : Unknown command received.";
                break;
            }


        }
    }
}

void ServerThread::onDisconnected()
{
    qDebug() << "客户端已断开连接:" << clientSocket->peerAddress().toString();
    quit();
}

void ServerThread::handleInsertChatHistory(QTcpSocket *clientSocket,int user_id_1,int user_id_2,ChatHistory history)
{
    qDebug() << "the ip "
             << clientSocket->peerAddress().toString()
             << " is trying to insert chat history";
    QDataStream out(clientSocket);

    if(dbManager.insertChatHistory(user_id_1,user_id_2,history.message_type,history.message)){
        out << INSERT_CHAT_HISTORY_OK
            << user_id_1
            << user_id_2;
    }else{
        out << INSERT_CHAT_HISTORY_ERROR;
    }

    clientSocket->flush();
    qDebug() << "reply over";

}

void ServerThread::handleUpdateUserInformation(QTcpSocket *clientSocket, User user)
{
    qDebug() << "the ip "
             << clientSocket->peerAddress().toString()
             << " is trying to update user";
    QDataStream out(clientSocket);
    if(dbManager.updateUser(user)){
        out << UPDATE_USER_INFORMATION_OK;
    }else{
        out << UPDATE_USER_INFORMATION_OK;
    }

    clientSocket->flush();
    qDebug() << "reply over";
}

void ServerThread::handleChatHistory(QTcpSocket *clientSocket,int user_one_id, int user_two_id)
{
    qDebug() << "the ip "
             << clientSocket->peerAddress().toString()
             << " is trying to get user chat history with "
             << user_one_id
             << " and "
             <<user_two_id;

    QList<ChatHistory> replyData = dbManager.getChatHistory(user_one_id,user_two_id);

    QDataStream out(clientSocket);

    if(replyData.size() == 0 || replyData.empty()){
        out << RETURN_CHAT_HISTORY_WITH_USER_ID_ERROR;
        clientSocket -> flush();
        qDebug() << "send over";
        return;
    }

    out << RETURN_CHAT_HISTORY_WITH_USER_ID_OK
        << user_one_id
        << user_two_id
        << static_cast<quint32>(replyData.size());      // 写入数据大小
    for(const ChatHistory &history : replyData)
    {
        qDebug() << "send one";
        out << history;
    }

    clientSocket -> flush();
    qDebug() << "send over";
}

void ServerThread::handleInformation(QTcpSocket *clientSocket,int user_id)
{
    qDebug() << "the ip "
             << clientSocket->peerAddress().toString()
             << " is trying to get user information with "<< user_id;
    User user = dbManager.getUserInformation(user_id);
    QDataStream out(clientSocket);

    if(user.id == -1)
    {
        out << RETURN_INFORMATION_WITH_USER_ID_ERROR;
        clientSocket -> flush();
        qDebug() << "send over";
    }
    out << RETURN_INFORMATION_WITH_USER_ID_OK
        <<user_id
        <<user;

    clientSocket -> flush();
    qDebug() << "send Over";
}
void ServerThread::handleFriendList(QTcpSocket *clientSocket,int user_id)
{
    qDebug() << "the ip "
             << clientSocket->peerAddress().toString()
             << " is trying to get friend list with "<< user_id;

    QList<Friend> replyData = dbManager.getFriendList(user_id);
    QDataStream out(clientSocket);

    if(replyData.empty() || replyData.size() == 0)
    {
        out << RETURN_FRIEND_LIST_WITH_USER_ID_ERROR;
        clientSocket -> flush();
        qDebug() << "send over";
    }

    out << RETURN_FRIEND_LIST_WITH_USER_ID_OK
        <<user_id
        <<static_cast<quint32>(replyData.size());
    for(const Friend &myFriend : replyData)
    {
        out << myFriend;
    }

    clientSocket -> flush();
    qDebug() << "send over";
}

void ServerThread::handleInsertUserInformation(QTcpSocket *clientSocket, User user)
{
    qDebug() << "ip "
             <<clientSocket -> peerAddress().toString()
             << "is trying to insert User information";

    bool flag = dbManager.insertUser(user);
    QDataStream out(clientSocket);

    qDebug() << "正在插入"
             <<"昵称：" << user.user_name
             <<"密码：" << user.user_password
             <<"id：" << user.id
             <<user.ip;

    if(flag)
    {
        out << INSERT_USER_OK;
    }else{
        out << INSERT_USER_ERROR;
    }

    clientSocket->flush();
    qDebug() << "send over";
    return;
}

void ServerThread::handleInsertFriendRelation(QTcpSocket *clientSocket, int user_one_id , int user_two_id){
    qDebug() << "ip"
             <<clientSocket->peerAddress().toString()
             <<"is trying to insert friend relation";

    qDebug() << user_one_id
             <<user_two_id;

    bool flag = dbManager.insertFriendRelation(user_one_id,user_two_id);
    QDataStream out(clientSocket);

    if(flag)
    {
        qDebug() << "reply INSERT_FRIEND_RELATION_OK";
        out << INSERT_FRIEND_RELATION_OK;
    }else
    {
        qDebug() << "reply INSERT_FRIEND_RELATION_ERROR";
        out <<INSERT_FRIEND_RELATION_ERROR;
    }
    clientSocket->flush();
    qDebug() << "send over";
    return;
}

void ServerThread::handleDeleteFriendRelation(QTcpSocket *clientSocket,int user_one_id,int user_two_id)
{
    qDebug() << "ip"
             <<clientSocket->peerAddress().toString()
             <<"is trying to delete friend relation";

    qDebug() << user_one_id
             <<user_two_id;

    bool flag = dbManager.deleteFriendRelation(user_one_id,user_two_id);
    QDataStream out(clientSocket);

    if(flag)
    {
        out << DELETE_FRIEND_RELATION_OK;
    }else{
        out <<DELETE_FRIEND_RELATION_ERROR;
    }
    clientSocket->flush();
    qDebug() << "send over";
    return;
}

